using UnityEngine;
using UnityEngine.EventSystems;

namespace Framework
{
    [DisallowMultipleComponent]
    public class UGUIWidget : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
    {
        [SerializeField]
        private string codePath = null;
        [SerializeField]
        private string bindClass = null;
        public string CodePath { get { return codePath; } }
        public RectTransform RectTransform { get; private set; }
        public UIWidget Widget { get; private set; }
        private void Awake()
        {
            RectTransform = GetComponent<RectTransform>();
            if (string.IsNullOrEmpty(bindClass))
            {
                FrameworkLog.LogWarningFormat("{0} bindClass is empty", this.name);
                return;
            }
            System.Type type = Utils.Assembly.GetType(bindClass);
            if (type == null)
            {
                FrameworkLog.LogWarningFormat("{0} not find class {1}", name, bindClass);
                return;
            }
            if (System.Activator.CreateInstance(type) is not UIWidget widget)
            {
                FrameworkLog.LogWarningFormat("{0} create class {1} failed!", name, bindClass);
                return;
            }
            this.Widget = widget;
            OnAwake();
            if (this.Widget != null)
            {
                this.Widget.Bind(this);
            }
        }
        protected virtual void OnAwake()
        {

        }
        public void OnPointerDown(PointerEventData eventData)
        {
            if (Widget == null) return;
            Widget.OnPointerDown(eventData);
        }
        public void OnPointerUp(PointerEventData eventData)
        {
            if (Widget == null) return;
            Widget.OnPointerUp(eventData);
        }
        protected virtual void OnDestroy()
        {
            if (this.Widget != null)
            {
                this.Widget.OnDestroy();
            }
            this.Widget = null;
        }
    }

}